package vn.com.vega.music.downloadmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.objects.Video;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.custom.ChaChaDialog;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

public class DownloadUtil {
	public static final int DOWNLOAD_SONG = 1;
	public static final int DOWNLOAD_VIDEO = 2;
	public static final int DOWNLOAD_LIST_SONG = 3;

	public static IDownloadService sService = null;

	private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();

	/**
	 * class ServiceBinder
	 * 
	 * @author Vega Corp
	 * 
	 */
	private static class ServiceBinder implements ServiceConnection {
		ServiceConnection mCallback;

		ServiceBinder(ServiceConnection callback) {
			mCallback = callback;
		}

		public void onServiceConnected(ComponentName className,
				android.os.IBinder service) {
			// Log.e(TAG, "before set sService");
			sService = IDownloadService.Stub.asInterface(service);
			if (mCallback != null) {
				mCallback.onServiceConnected(className, service);
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			if (mCallback != null) {
				mCallback.onServiceDisconnected(className);
			}
			sService = null;
		}
	}

	/**
	 * Class ServiceToken
	 * 
	 * @author Vega Corp
	 * 
	 */
	public static class ServiceToken {
		ContextWrapper mWrappedContext;

		ServiceToken(ContextWrapper context) {
			mWrappedContext = context;
		}
	}

	public static ServiceToken bindToService(Activity context) {
		return bindToService(context, null);
	}

	public static ServiceToken bindToService(Activity context,
			ServiceConnection callback) {
		Activity realActivity = context.getParent();
		if (realActivity == null) {
			realActivity = context;
		}
		ContextWrapper cw = new ContextWrapper(realActivity);
		cw.startService(new Intent(cw, DownloadService.class));
		ServiceBinder sb = new ServiceBinder(callback);
		if (cw.bindService((new Intent()).setClass(cw, DownloadService.class),
				sb, 0)) {
			sConnectionMap.put(cw, sb);
			return new ServiceToken(cw);
		}
		Log.e("Music", "Failed to bind to service");
		return null;
	}

	public static void unbindFromService(ServiceToken token) {
		if (token == null) {
			Log.e("MusicUtils", "Trying to unbind with null token");
			return;
		}
		ContextWrapper cw = token.mWrappedContext;
		ServiceBinder sb = sConnectionMap.remove(cw);
		if (sb == null) {
			Log.e("MusicUtils", "Trying to unbind for unknown Context");
			return;
		}
		cw.unbindService(sb);
		if (sConnectionMap.isEmpty()) {
			// presumably there is nobody interested in the service at this
			// point,
			// so don't hang on to the ServiceConnection
			sService = null;
		}
	}

	private static boolean downloadSong(final Song song, Activity act) {
		if (sService == null) {
			ServiceConnection connection = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					// TODO Auto-generated method stub
					downloadSong(song);
				}
			};
			bindToService(act, connection);
		} else {
			return downloadSong(song);
		}
		return true;
	}

	private static boolean downloadSong(Song song) {
		if (sService != null) {
			try {
				return sService.addSongtoDownloadList(song);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	private static boolean downloadVideo(Video video) {
		if (sService != null) {
			try {
				return sService.addVideoToDownloadList(video);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	private static boolean downloadVideo(final Video video, Activity act) {
		if (sService == null) {
			ServiceConnection connection = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					// TODO Auto-generated method stub
					downloadVideo(video);
				}
			};
			bindToService(act, connection);
		} else {
			return downloadVideo(video);
		}
		return true;
	}

	private static boolean downloadListSong(final List<Song> listSong,
			Activity act) {
		if (sService == null) {
			ServiceConnection connection = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					// TODO Auto-generated method stub
					downloadListSong(listSong);
				}
			};
			bindToService(act, connection);
		} else {
			return downloadListSong(listSong);
		}
		return true;
	}

	private static boolean downloadListSong(List<Song> listSong) {
		if (sService != null) {
			try {
				return sService.addListSongtoDownloadList(listSong);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return false;
	}

	public static boolean checkVideoInListDownload(Video video) {
		if (sService != null) {
			try {
				return sService.videoExitInDownloadList(video);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public static boolean checkSongIsInListDownload(Song song) {
		if (sService != null) {
			try {
				return sService.songExitInDownloadList(song);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public static void unbindAll() {
		try {
			Set<Context> listContext = sConnectionMap.keySet();
			for (Context ctx : listContext) {
				ServiceBinder serviceBinder = sConnectionMap.remove(ctx);
				if (serviceBinder != null) {
					ctx.unbindService(serviceBinder);
				}
			}
			sConnectionMap.clear();
			sService = null;
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public static void stopDownload() {
		if (sService != null) {
			try {
				sService.stopDownload();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		unbindAll();
	}

	private static void download(int type, List<Object> listObjectDownload, Activity act) {
		switch (type) {
		case DOWNLOAD_SONG:
			Song song = (Song) listObjectDownload.get(0);
			downloadSong(song, act);
			break;
		case DOWNLOAD_VIDEO:
			Video video = (Video) listObjectDownload.get(0);
			downloadVideo(video, act);
			break;
		case DOWNLOAD_LIST_SONG:
			List<Song> listSong = new ArrayList<Song>();
			for (Object obj : listObjectDownload) {
				Song songDownload = (Song) obj;
				listSong.add(songDownload);
			}
			downloadListSong(listSong, act);
			break;

		default:
			break;
		}
	}
	
	public static void downLoad(final int type, final List<Object> listObjectDownload,
			final Activity act, String warningMessage, boolean showRegister) {
		if (Util.checkStringIsemptyOrNull(warningMessage)) {
			download(type, listObjectDownload, act);
		} else {
			final ChaChaDialog chaChaDialog = new ChaChaDialog(act, null);
			chaChaDialog.setCancelable(false);
			chaChaDialog.setTitle("Thông báo");
			chaChaDialog.setMessage(warningMessage);
			
			View.OnClickListener confirmYes = new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					chaChaDialog.dismiss();
					download(type, listObjectDownload, act);
				}
			};
			
			View.OnClickListener confirmNo = new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					chaChaDialog.dismiss();
				}
			};
			chaChaDialog.addButton("Tải về", confirmYes);
			chaChaDialog.addButton("Không", confirmNo);
			
			if (showRegister) {
				View.OnClickListener confirmRegister = new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						chaChaDialog.dismiss();
						Appinstant app = (Appinstant) act.getApplication();
						Handler handler = new Handler();
						app.register(act, null, handler, false, null);
					}
				};
				chaChaDialog.addButton("Đăng kí", confirmRegister);
			}
		}
	}

}
